# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from django.db import models
from django.template.defaultfilters import slugify

from django.dispatch import dispatcher
from django.contrib.auth.models import User, Group
from libs.signals import *
from apps.core.models.section import Section
#from libs.utils import plug_core
from django.db.models import Q

STATUS_CHOICES = [(0, 'Privato'), (1, 'Shared'), (2, 'Da approvare'), (3, 'Pubblico'),]

class ElementManager(models.Manager):
    def getElements(self,user,element):
        if user.is_authenticated():
            return Element.objects.filter(Q(etype__exact=element), Q(status__exact=3)| Q(owner__exact=user) & Q(status__exact=0) |
                                          Q(status__exact=1) & Q(group__in=user.groups.all())).distinct()
        else:
            return Element.objects.filter(status__exact=3)

    def getElement(self,user,eid):
        if user.is_authenticated():
            return Element.objects.filter(Q(id__exact=eid), Q(status__exact=3)| Q(owner__exact=user) & Q(status__exact=0) |
                                          Q(status__exact=1) & Q(group__in=user.groups.all())).distinct()[0]
        else:
            return Element.objects.filter(Q(id__exact=eid), Q(status__exact=3)).distinct()[0]
    
    def getPending(self,user,element):
        if user.is_authenticated():
            return Element.objects.filter(etype__exact=element, owner__exact=user, status__exact=2)
        else:
            return []
        
    def getForSection(self,user,section):
        if user.is_authenticated():
            return Element.objects.filter(Q(section__exact=section), Q(status__exact=3) | Q(owner__exact=user) & Q(status__exact=0) |
                                          Q(status__exact=1) & Q(group__in=user.groups.all())).distinct()
        else:
            return Element.objects.filter(status__exact=3)

class Element(models.Model):
    # Descrizione
    title = models.CharField(max_length=255)
    subtitle = models.CharField(max_length=255, blank=True)
    order = models.IntegerField(default=0)
    etype = models.CharField(max_length=255)
    
    # Date
    creation_date = models.DateTimeField(editable=False)
    last_update = models.DateTimeField(editable=False)
    publication_start = models.DateTimeField(blank=True)
    publication_end = models.DateTimeField(blank=True, null=True)
    status = models.IntegerField(choices=STATUS_CHOICES)
    
    # Dipendenze
    section = models.ForeignKey(Section)
    owner = models.ForeignKey(User)
    owner_alias = models.CharField(max_length=100, blank=True)
    group = models.ManyToManyField(Group, null=True, blank=True)
      
    # Seo
    slug = models.SlugField()
    keywords = models.TextField(blank=True)

    objects = ElementManager()
    
    def save(self):
        import libs.plug_core as plug_core
        _need_to_be_raised = False
        mymodel = None
        self.last_update = datetime.datetime.now()
        if not self.creation_date:
            self.creation_date = datetime.datetime.now()
        if self.slug == "": 
            self.slug = slugify(self.title)
        else: 
            self.slug = slugify(self.slug) 
        if not self.publication_start:
            self.publication_start = datetime.datetime.now()
        if self.id != None:
            e = Element.objects.get(id= self.id)
            if e.status == 2 and self.status != 2:
                _need_to_be_raised=True
                mymodel = plug_core.get_model_from_etype(self.etype)
        super(Element, self).save()
        if _need_to_be_raised:
            dispatcher.send(signal=element_approved, sender=mymodel , instance=self)
        
    def __unicode__(self):
        return self.title
    
    class Meta:
        app_label = 'core'
        permissions= (
            ("can_mod_perms", "Can Modify Permissions"),
            )
